package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.EnRecruit;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.AdminPiInfoConvert;
import cn.com.hhrcw.params.PiInfoParams;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.vo.PiInfoVO;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;

/**
 * 招聘者信息
 *
 * @author gaoruiyi
 * @since 2020-11-06
 */
@RestController
@Slf4j
@RequestMapping("/admin/enRecruit")
@Api(tags = "招聘者信息")
@Validated
public class EnRecruitController extends JeecgController<EnRecruit, IEnRecruitService> {

    @Autowired
    private IPiInfoService pinfoService;

    @Autowired
    private AdminPiInfoConvert enPiInfoConvert;

    @Autowired
    AdminService enterpriseService;

    @Autowired
    IFileService fileService;

    @Autowired
    private IOpJobService jobService;

    @Autowired
    IOpDeliveryHistoryService historyService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 同事列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(value = "同事列表", logType = 2, ty = "visit")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<PiInfoVO>> list(PiInfoParams params, HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<PiInfo> initQueryWrapper = QueryGenerator.initQueryWrapper(enPiInfoConvert.toEntity(params), request.getParameterMap());
        if (params.getStatus() != null) {
            initQueryWrapper.eq("status", params.getStatus());
        }
        initQueryWrapper.eq("pi_info.del_flag", false);
        initQueryWrapper.orderByDesc("pi_info.create_time DESC,status ASC ,pi_info.id");

        if (StringUtils.isNotBlank(params.getQueryValue())) {
            initQueryWrapper.and(wrapper -> wrapper.like("pi_info.name", params.getQueryValue()).or().like("pi_info.email", params.getQueryValue()).or().like("pi_info.phone", params.getQueryValue()));
        }

        LambdaQueryWrapper<PiInfo> queryWrapper = initQueryWrapper.lambda();
        queryWrapper.like(PiInfo::getRoleType, "2");
        IPage<PiInfo> page = pinfoService.selectJoinUserPage(queryWrapper, params.page());
        //分页结果转换器
        Function<PiInfo, PiInfoVO> fun = piInfo -> {
            SysUser user = this.sysUserService.getById(piInfo.getUserId());
            PiInfoVO vo = enPiInfoConvert.toVO(piInfo);
            vo.setStatus(user.getStatus());
            List<OpJob> jobCount = jobService.lambdaQuery().eq(OpJob::getDelFlag, false).eq(OpJob::getRecruitmentState, 0).eq(OpJob::getCreateBy, sysUser.getId()).list();
            vo.setOnlineJobCount(CollectionUtils.isEmpty(jobCount) ? 0 : jobCount.size());
            if (!CollectionUtils.isEmpty(jobCount)) {
                List<String> jobId = new ArrayList<>();
                jobCount.forEach(e -> {
                    jobId.add(e.getId());
                });
                Integer seven = historyService.seven(jobId);
                vo.setSevenCount(seven);
            }
            return vo;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 批量冻结
     *
     * @return
     */
    @PostMapping("/disableAccount")
    public Result disableAccount(@RequestBody List<String> id) {
        Assert.notEmpty(id, "请选择要冻结的记录");
        Collection<PiInfo> piInfos = this.pinfoService.listByIds(id);
        Object[] userIds = piInfos.stream().map(PiInfo::getUserId).toArray();
        boolean update = this.sysUserService.lambdaUpdate()
            .in(SysUser::getId, userIds)
            .ne(SysUser::getUsername, "admin")
            .set(SysUser::getStatus, 2)
            .update();
        Assert.isTrue(update, "冻结失败");
        return Result.ok();
    }

    /**
     * 解冻
     *
     * @return
     */
    @PostMapping("/enableAccount")
    public Result enableAccount(@RequestBody List<String> id) {
        Assert.notEmpty(id, "请选择要解冻的记录");
        Collection<PiInfo> piInfos = this.pinfoService.listByIds(id);
        Object[] userIds = piInfos.stream().map(PiInfo::getUserId).toArray();
        boolean update = this.sysUserService.lambdaUpdate()
            .in(SysUser::getId, userIds)
            .set(SysUser::getStatus, 1)
            .update();
        Assert.isTrue(update, "解冻失败");
        return Result.ok();
    }

    public static void main(String[] args) {
        System.out.println(PasswordUtil.encrypt("146172", "123123", "KW3YdoxL"));
    }

}
